package systempen.cmanager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.achartengine.ChartFactory;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.MultipleCategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import systempen.cmanager.DialogAccountBrowser.IFoundAccount;
import systempen.cmanager.DialogTypeBrowser.IFoundCostType;
import systempen.cmanager.R;
import android.R.array;
import android.R.string;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

public class ReportDoublePieParams extends AcitivityLowImportance {
	Activity thisclass;
	public TextView textFrom1;
	public TextView textTo1;
	public TextView textFrom2;
	public TextView textTo2;
	public TextView textAccountName;


	static final int DATE_DIALOG_ID_from1 = 0;
	static final int DATE_DIALOG_ID_to1 = 1;
	static final int DATE_DIALOG_ID_from2 = 2;
	static final int DATE_DIALOG_ID_to2 = 3;
	SQLiteDatabase db;
	String level;
	public TextView textCost;
	Cursor c1;
	Cursor c2;
	String sqlDebug1;
	String sqlDebug2;
	String foundedType;
	Boolean restart;
	String _accountCode; 

	@Override
	public void onCreate(Bundle savedInstanceState) {
		try{
			super.onCreate(savedInstanceState);
			ThemePicker.onActivityCreateSetTheme(this);
			setContentView(R.layout.report_double_params);
			thisclass = this;
			textFrom1 = (TextView) findViewById(R.id.txtPeriod1From);
			textTo1 = (TextView) findViewById(R.id.txtPeriod1To);
			textFrom2 = (TextView) findViewById(R.id.txtPeriod2From);
			textTo2 = (TextView) findViewById(R.id.txtPeriod2To);
			level = "0";
			textAccountName = (TextView) findViewById(R.id.txtAccountName);
			textCost = (TextView) findViewById(R.id.txtTypeName);
			textFrom1.setText(util.dbStringDateToViewStringDate(util.GetLastMonthPeriodDB().a.toString(), thisclass)); 
			textTo1.setText(util.dbStringDateToViewStringDate(util.GetLastMonthPeriodDB().b.toString(), thisclass));
			textFrom2.setText(util.getDefaultFromDateView(getApplicationContext()));
			textTo2.setText(util.getDefaultToDateView(getApplicationContext()));


		} catch(Exception ex){
			util.showDialog(ex.getMessage().toString(), thisclass);
		}
	}
	@Override
	public void onRestart(){
		super.onRestart();
		//startActivity(new Intent(this, MainActivityTab.class));
	}

	public void onRunReport (View view){
		try{
			String podtipovi = util.getAllChildren(level, thisclass);
			String sqlAccount;
			if ((_accountCode!=null)&&(!_accountCode.equals(""))){
				sqlAccount = " and log.account = "+ _accountCode+" ";
			}
			else
			{
				sqlAccount = "";
			}
			sqlDebug1 = " select sum(value) as sum,cost_code, cost_type.name "+
					" from log join cost_type on log.cost_code = cost_type.code "+
					" where log.whe >= '"+util.viewStringDateToDBStringDate(textFrom1.getText().toString(), getApplicationContext()) +"'"+
					" and log.whe <= '"+util.viewStringDateToDBStringDate(textTo1.getText().toString(), getApplicationContext()) +"'"+
					" and cost_type.code in("+podtipovi+")"+
					" and value > 0 "+
					sqlAccount +
					" group by cost_code, cost_type.name";
			sqlDebug2 = " select sum(value) as sum,cost_code, cost_type.name "+
					" from log join cost_type on log.cost_code = cost_type.code "+
					" where log.whe >= '"+util.viewStringDateToDBStringDate(textFrom2.getText().toString(), getApplicationContext()) +"'"+
					" and log.whe <= '"+util.viewStringDateToDBStringDate(textTo2.getText().toString(), getApplicationContext()) +"'"+
					" and cost_type.code in("+podtipovi+")"+
					" and value > 0 "+
					sqlAccount +
					" group by cost_code, cost_type.name";
			util u1 = new util();
			util u2 = new util();
			c1 = u1.getCursor(sqlDebug1, thisclass);
			c2 = u2.getCursor(sqlDebug2, thisclass);
			if (c1.getCount()==0){
				Toast.makeText(getApplicationContext(), "No data effected, first period.", Toast.LENGTH_SHORT).show();
				c1.close();
				c2.close();
				u1.db.close();
				u2.db.close();
				return;
			}
			if (c2.getCount()==0){
				Toast.makeText(getApplicationContext(), "No data effected, second period.", Toast.LENGTH_SHORT).show();
				c2.close();
				c1.close();
				u1.db.close();
				u2.db.close();
				return;
			}
			startActivity(new ReportDoublePieParams().execute(this,c1,c2));
		} catch(Exception ex){
			//util.showDialog(ex.getMessage().toString(), thisclass);
			Toast.makeText(ReportDoublePieParams.this, ex.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	////////////
	public Intent execute(Context context,Cursor c1, Cursor c2) {
		try{
			Random r = new Random();
			///uzimanje podataka
			CategorySeries categorySeries = new CategorySeries("Costs Chart");
			int n = c1.getCount();
			int[] colors2 = new int[n];
			List nazivi = new ArrayList();
			List unutrasnji = new ArrayList(); 
			List vanjski = new ArrayList();
			c1.moveToFirst();
			c2.moveToFirst();
			int i = 0;
			int j = 0;
			if (c1.moveToFirst()) { 
				do {
					if(c2.moveToFirst()){
						do{
							if(c1.getString(2).equals(c2.getString(2))){//znaci slazu se
								nazivi.add(c1.getString(2));
								unutrasnji.add(c1.getDouble(i));
								vanjski.add(c2.getDouble(i));
								break;
							}
						}while(c2.moveToNext());
					}
				} 
				while (c1.moveToNext());
			}
			String[] nazivi1 = (String[]) nazivi.toArray(new String[nazivi.size()]);
			double[] unutrasnji1 = new double[nazivi.size()];  
			double[] vanjski1 = new double[nazivi.size()];
			int k = 0;
			while (k < unutrasnji.size()) {
				unutrasnji1[k] = (Double) unutrasnji.get(k);
				colors2[k] = Color.rgb(r.nextInt(256), r.nextInt(256), r.nextInt(256));
				k++;
			}
			k=0;
			while (k < unutrasnji.size()) {
				vanjski1[k] = (Double) vanjski.get(k);
				k++;
			}
			k=0;


			DefaultRenderer renderer = buildCategoryRenderer(colors2);
			renderer.setApplyBackgroundColor(true);
			renderer.setBackgroundColor(Color.rgb(222, 222, 200));
			renderer.setLabelsColor(Color.BLACK);
			List<double[]> values = new ArrayList<double[]>();
			values.add(unutrasnji1);
			values.add(vanjski1);
			MultipleCategorySeries mc = new MultipleCategorySeries("titl");
			mc.add(nazivi1,vanjski1);		    
			mc.add(nazivi1,unutrasnji1);
			return ChartFactory.getDoughnutChartIntent(context, mc ,renderer, "Doughnut chart");


			//DefaultRenderer renderer = buildCategoryRenderer(colors2);
			//return ChartFactory.getPieChartIntent(context, categorySeries, renderer,"Costs distribution");
		}
		catch(Exception ex){
			Toast.makeText(ReportDoublePieParams.this, ex.getMessage(), Toast.LENGTH_SHORT).show();        	return null;
		}	
	}

	protected DefaultRenderer buildCategoryRenderer(int[] colors) {
		DefaultRenderer renderer = new DefaultRenderer();
		for (int color : colors) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(color);

			renderer.addSeriesRenderer(r);
			renderer.setShowAxes(true);
			renderer.setLegendTextSize(26);
			renderer.setLabelsTextSize(22);
			renderer.setAntialiasing(true);
		}
		return renderer;
	}
	////////////

	public void onChangeFrom1Date (View view){
		try{
			showDialog(DATE_DIALOG_ID_from1);
		} catch(Exception ex){
			util.showDialog(ex.getMessage().toString(), thisclass);
		}
	}
	public void onChangeTo1Date (View view){
		try{
			showDialog(DATE_DIALOG_ID_to1);
		} catch(Exception ex){
			util.showDialog(ex.getMessage().toString(), thisclass);
		}
	}
	public void onChangeFrom2Date (View view){
		try{
			showDialog(DATE_DIALOG_ID_from2);
		} catch(Exception ex){
			util.showDialog(ex.getMessage().toString(), thisclass);
		}
	}
	public void onChangeTo2Date (View view){
		try{
			showDialog(DATE_DIALOG_ID_to2);
		} catch(Exception ex){
			util.showDialog(ex.getMessage().toString(), thisclass);
		}
	}


	// Creating dialog
	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance();
		int cyear = c.get(Calendar.YEAR);
		int cmonth = c.get(Calendar.MONTH);
		int cday = c.get(Calendar.DAY_OF_MONTH);
    	Context contekst = getParent();
    	if (contekst==null)
    	{
    		contekst = this;
    	}
		switch (id) {
		case DATE_DIALOG_ID_from1:
			return new DatePickerDialog(contekst,  mDateSetListener,  cyear, cmonth, cday);
		case DATE_DIALOG_ID_to1:
			return new DatePickerDialog(contekst,  mDateSetListener2,  cyear, cmonth, cday);
		case DATE_DIALOG_ID_from2:
			return new DatePickerDialog(contekst,  mDateSetListener3,  cyear, cmonth, cday);
		case DATE_DIALOG_ID_to2:
			return new DatePickerDialog(contekst,  mDateSetListener4,  cyear, cmonth, cday);
		}
		return null;
	}
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		// onDateSet method
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			try{
				//String date_selected = String.valueOf(monthOfYear+1)+" /"+String.valueOf(dayOfMonth)+" /"+String.valueOf(year);
				String date_selected = String.valueOf(year)+"-"+util.AddZeros(monthOfYear+1)+"-"+util.AddZeros(dayOfMonth);

				Toast.makeText(ReportDoublePieParams.this, "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
				textFrom1.setText(util.dbStringDateToViewStringDate(date_selected, getApplicationContext()));
			}
			catch(Exception ex){
				util.showDialog(ex.getMessage().toString(), thisclass);
			}	
		}
	};
	private DatePickerDialog.OnDateSetListener mDateSetListener2 = new DatePickerDialog.OnDateSetListener() {
		// onDateSet method
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			try{
				String date_selected = String.valueOf(year)+"-"+util.AddZeros(monthOfYear+1)+"-"+util.AddZeros(dayOfMonth);
				Toast.makeText(ReportDoublePieParams.this, "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
				textTo1.setText(util.dbStringDateToViewStringDate(date_selected, getApplicationContext()));
			}
			catch(Exception ex){
				util.showDialog(ex.getMessage().toString(), thisclass);
			}	
		}
	};
	private DatePickerDialog.OnDateSetListener mDateSetListener3 = new DatePickerDialog.OnDateSetListener() {
		// onDateSet method
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			try{
				//String date_selected = String.valueOf(monthOfYear+1)+" /"+String.valueOf(dayOfMonth)+" /"+String.valueOf(year);
				String date_selected = String.valueOf(year)+"-"+util.AddZeros(monthOfYear+1)+"-"+util.AddZeros(dayOfMonth);

				Toast.makeText(ReportDoublePieParams.this, "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
				textFrom2.setText(util.dbStringDateToViewStringDate(date_selected, getApplicationContext()));
			}
			catch(Exception ex){
				util.showDialog(ex.getMessage().toString(), thisclass);
			}	
		}
	};
	private DatePickerDialog.OnDateSetListener mDateSetListener4 = new DatePickerDialog.OnDateSetListener() {
		// onDateSet method
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			try{
				String date_selected = String.valueOf(year)+"-"+util.AddZeros(monthOfYear+1)+"-"+util.AddZeros(dayOfMonth);
				Toast.makeText(ReportDoublePieParams.this, "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
				textTo2.setText(util.dbStringDateToViewStringDate(date_selected, getApplicationContext()));
			}
			catch(Exception ex){
				util.showDialog(ex.getMessage().toString(), thisclass);
			}	
		}
	};

	public void onChooseType (View view){
		IFoundCostType ifo = new IFoundCostType() {

			@Override
			public void onFoundCostType(String costType) {
				level = costType;
				foundedType = util.getLevelName(costType, getApplicationContext());
				textCost.setText(foundedType); 
			}
		};
    	Context contekst = getParent();
    	if (contekst==null)
    	{
    		contekst = this;
    	}
		DialogTypeBrowser dt = new DialogTypeBrowser(contekst, "0", ifo);
		dt.show();
	}
	public void onChooseAccount(View v){
		IFoundAccount ifa = new IFoundAccount() {

			@Override
			public void onFoundAccount(String account) {
				// TODO Auto-generated method stub
				_accountCode = account;
				textAccountName.setText(util.getAccountName(account, getApplicationContext()));
			}
		};
    	Context contekst = getParent();
    	if (contekst==null)
    	{
    		contekst = this;
    	}
		DialogAccountBrowser dab = new DialogAccountBrowser(contekst, ifa);
		dab.show();
	}
}
